package com.example.demo.controller;

import com.example.demo.domain.AgeCount;
import com.example.demo.domain.Elder;
import com.example.demo.result.RespBean;
import com.example.demo.service.ElderServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.sql.Timestamp;
import java.util.List;

@RestController
@RequestMapping(value = "/ElderManage")
@CrossOrigin
public class ElderController {
    @Autowired
    private ElderServiceImpl elderService;

    @GetMapping(value = "/findAll")
    @ResponseBody
    public RespBean findAll(){
        List<Elder> elders;
        elders = elderService.findAll();
        return RespBean.success("success",elders);
    }

    @GetMapping(value = "/findOneElder")
    @ResponseBody
    public RespBean findOneElder(@RequestParam("elder_id") int id){
        Elder elder;
        elder = elderService.selectElder(id);
        return RespBean.success("success",elder);
    }

    @GetMapping(value = "/deleteOneElder")
    @ResponseBody
    public RespBean deleteElder(@RequestParam("elder_id") int id){
        elderService.deleteElder(id);
        return RespBean.success("success");
    }

    @PostMapping(value = "/addElder")
    @ResponseBody
    public RespBean addElder(@RequestBody @Valid Elder elder){
        Timestamp d = new Timestamp(System.currentTimeMillis());
        elder.setCreated(d.toString());
        elder.setImgset_dir("/img/elder");
        elder.setProfile_photo("/elder/profile/");
        elderService.addElder(elder);
        return RespBean.success("success");
    }

    @PostMapping(value = "/updateElder")
    @ResponseBody
    public RespBean updateElder(@RequestBody @Valid Elder elder){
        elderService.updateElder(elder);
        return RespBean.success("success");
    }

    @GetMapping(value = "/selectByAge")
    @ResponseBody
    public RespBean SelectAge(){
        AgeCount ageCount = new AgeCount();
        int[] age = new int[4];
        age[0] = elderService.selectAge(1,59);
        age[1] = elderService.selectAge(60,69);
        age[2] = elderService.selectAge(70,79);
        age[3] = elderService.selectAge(80,150);
        ageCount.setAge(age);
        return RespBean.success("success",ageCount);
    }
}
